﻿<?php
class Customer_CustomerController extends Zend_Controller_Action {

    /**======================Back-end=========================*/
    public function infoAction(){
        $request = $this->getRequest();

        $user_id = $request->getParam('user_id');
        $this->view->assign('user_id', $user_id);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        $user = $userDao->getById($user_id);
        $this->view->assign('user', $user);
    } 

    /**=======================Front end=======================*/
	/**
	* Cancel Order
	**/
	public function cancelOrderAction(){
		$conn = Tomato_Db_Connection::factory()->getMasterConnection();
		/**
		* Enterprise User model access to db
		*/
		$orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
		$orderDao->setDbConnection($conn);
		try{
			$request     = $this->getRequest(); 
			$order_id    = $request->getParam('order_id',null);		
			if($order_id){
				$orderObj = 	$orderDao->getOrderById($order_id);				
				if($orderObj){
					$auth = Zend_Auth::getInstance();
					if ($auth->hasIdentity()){
						$user    = $auth->getIdentity();
						$user_id = $user->user_id;
						if($user_id != $orderObj->customer_id)
							throw new Exception("Bạn không được hủy hóa đơn của người khác.");
						else{	
							$orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
							$orderDao->setDbConnection($conn);
							$orderDao->updateOrderStatusInvalid($order_id);
							$res = array("success"=>true);
						}
					}else
						throw new Exception("Chưa đăng nhập");					
				}				
			}else
				throw new Exception("Mã hóa đơn chưa có.");			
		}catch(Exception $ex){
			$res = array("success"=>false,"msg"=>$ex->getMessage());	
		}		
		echo Zend_json::encode($res);die;
	}
	
    /**
    * List of customer
    * @return void
    **/
    public function listAction(){
        $request = $this->getRequest(); 
		        		
        $user_name = $request->getParam('user_name');
        
        $lang = $request->getParam('lang');
        $this->view->assign('lang', $lang);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
        * Customer models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * Order model access to data
         **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);
        
        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);
		
		/**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
         * Evaluation basic model access to data
         */
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
         * Enterprise model access to data
         */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);
        
        /**
         * Customer models of Customer access to data
        **/
        $cusDao = Tomato_Model_Dao_Factory::getInstance()->setModule('customer')->getCustomerDao();
        $cusDao->setDbConnection($conn);

        /**
        * Check no login yet
        **/
        $auth = Zend_Auth::getInstance();
        $userSession = $auth->getIdentity();
        $this->view->assign('userSession', $userSession);

        /**
        * Get user info
        **/
        $user = $userDao->getByUserName($user_name);        
        if(!$user){
        	$this->view->assign('no_exist', true);
            return;
        }
        
        //Get enterprise account to check permission      
        $enterprise_id = null;
        $userAccount = $userAccountDao->getByUser($user->user_id);
        if($userAccount){
            $enterprise_id = $userAccount->enterprise_id;
        }
        $this->view->assign('user_enterprise', $enterprise_id);
        
        //Check allow action        
        $isAllowAction = false;
        if(@$userSession->user_id == $user->user_id){
            $isAllowAction = true;
        }
        $this->view->assign('isAllowAction', $isAllowAction);

        /**
         * Assign user to view
        **/
        $this->view->assign('user', $user);     
        
        
        
/*=============================Quan dang sua=================================*/   
        
        //Check is enterprise or user        
        $isEnterprise = false;
        $exp_id       = null;
        if($enterprise_id){
            //Get point and counter            
            $avergePC = $enterpriseDao->getById($enterprise_id);
            $exp_id = $enterprise_id;
            $isEnterprise = true;
        }
        else{
            //Get point and counter
            $avergePC = $cusDao->getById($user->user_id);
            $exp_id = $user->user_id;
        }
        $this->view->assign('avergePC', $avergePC);
        //$this->view->assign('exp_id', $exp_id);
        //$this->view->assign('isEnterprise', $isEnterprise);
        
/*=============================end Quan dang sua=================================*/
        
        
        //Get customer info follow user
        $customer = null;
        $flag = false;
        if($user){
            $customer = $customerDao->getCustomer($user->user_id);
            
			//Check order of user is exist with status diff close            
            $orders = $orderDao->getOByU($user->user_id);
            if(count($orders) > 0){
                foreach($orders as $order){
                    $process = $assignmentDao->getPSById($order->process_id);
                    if($process->code != 'close'){
                        $flag = true;
                        break;
                    }
                }
            }else{
                $flag = false;
            }
        }
        $this->view->assign('customer', $customer);
        $this->view->assign('flag', $flag);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 10;
        $offset    = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp = array();

        $exp['order_status'] = 'valid';

        /**
        * Check user is enterprise or customer
        **/
        $isEnterprise = false;       
      
        if($userAccount){
            $isEnterprise = true;
            /*$enterprise_id = (null != $userAccount->enterprise_id)?$userAccount->enterprise_id:null;
            $exp['enterprise_id'] = $purifier->purify($enterprise_id);           
            $exp['or_customer_id'] = $purifier->purify($user->user_id);*/
           
            $enterprise_info = $enterpriseDao->getById($enterprise_id);
            $this->view->assign('enterprise_info', $enterprise_info);
        }
        /*else{
            $exp['customer_id'] = $purifier->purify($user->user_id);            
        }*/
        $exp['customer_id'] = $purifier->purify($user->user_id);
        
        
        
        $this->view->assign('isEnterprise', $isEnterprise);

        $orders = $orderDao->find($offset, $perPage, $exp);
        $numOrder = $orderDao->count($exp);

        /**
         * $arrStatus: array object status
        **/

        $arrStatus = array();
        $arrEvalOrders = array();
        foreach($orders as $r_order){
            /**
            * Get tracking status info
            **/
            if($r_order->process_id){
                $status = $assignmentDao->getPSById($r_order->process_id);
                $arrStatus[$r_order->order_id] = $status->code;
            }

            /**
             * Check seller or buyer no evaluated yet
            **/
            $eval_exp['order_id'] = $r_order->order_id;
            $eval_orders = $evaluationDao->getById($eval_exp);
            $arrEvalOrders[$r_order->order_id] = $eval_orders;
             
        }
        
        $this->view->assign('arrStatus', $arrStatus);
        $this->view->assign('arrEvalOrders', $arrEvalOrders);

        /** Paginator*/
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($orders, $numOrder));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('perPage', $perPage);
        $this->view->assign('orders', $orders);
        $this->view->assign('numOrder', $numOrder);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array('user_name' => $user->user_name), 'customer_customer_list'),
            'itemLink' => (null == $params)
                            ? 'page-%d/'
                            : 'page-%d/?q=' . $params,
        ));
    }

    /**
     * View customer info
     * @return void
     **/
    public function viewAction() {
        $request = $this->getRequest();
        $order_id = $request->getParam('order_id');
        $lang = $request->getParam('lang');

        $user_name = $request->getParam('user_name');

        /**
        * Check no login yet
        **/
        $auth = Zend_Auth::getInstance();
        $userSession = $auth->getIdentity();
        if (!$userSession) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * user model access to data
         **/
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * Order model access to data
         **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
        * Attribute model access to db
        */
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to db
        */
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $cartDao->setLang($lang);

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Get user info
        **/
        $user = $userDao->getByUserName($user_name);
        $this->view->assign('user', $user);

        /**
         * Check allow action
        **/
        $isAllowAction = true;
        if(@$userSession->user_id != @$user->user_id){
            $isAllowAction = false;
            $this->view->assign('isAllowAction', $isAllowAction);
            return;
        }
        $this->view->assign('isAllowAction', $isAllowAction);

        /**
         * Order info
        **/
        $order = $orderDao->getOrderById($order_id);
        $this->view->assign('order', $order);

        /**
         * Get enterprise account to check permission
        */
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
         * Check user belong to enterprise
        **/
        $user_enterprise = null;
        if(isset($userAccount->enterprise_id)){
            $user_enterprise = $userAccount->enterprise_id;
        }
        $this->view->assign('user_enterprise', $user_enterprise);

        /**
        * Check permission to view order detail
        **/
        $isAllowed = true;
        if(isset($userAccount->enterprise_id) && isset($order->enterprise_id)){
            if($userAccount->enterprise_id != $order->enterprise_id && $user->user_id != $order->customer_id){
                $isAllowed = false;
                $this->view->assign('isAllowed', $isAllowed);
                return;
            }
        }else{
            if($user->user_id != $order->customer_id){
                $isAllowed = false;
                $this->view->assign('isAllowed', $isAllowed);
                return;
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        $sEvaluated = false;
        $bEvaluated = false;
        if(isset($userAccount->enterprise_id)){
            if($userAccount->enterprise_id == $order->enterprise_id){
                $sEvaluated = true;
            }else{
                $bEvaluated = true;
            }
        }else{
            $bEvaluated = true;
        }
        $this->view->assign('bEvaluated', $bEvaluated);
        $this->view->assign('sEvaluated', $sEvaluated);

        /**
         * Get status for assignment
        **/
        $status = null;
        $objstatus = null;
        if($order->process_id){
            $objstatus = $assignmentDao->getPSById($order->process_id);
            if($objstatus){
                $status =$objstatus->code;
            }
        }
		$_status = $status;
        $this->view->assign('status', $status);

        /**
         * Get follow process for assignment
        **/
        $arrProcess = array();
        if($objstatus){
            $arrProcess = explode(',',substr(substr($objstatus->follow_process_id_chain,1),0,-1));
        }
        $this->view->assign('arrProcess', $arrProcess);

        /**
         * Get follow step for assignment
         * $arrSteps: store follow step
         * $strRoleId String performer_role_id_chain to check permission
        **/
        $arrSteps = array();
        $strRoleId = null;
        if($objstatus){
            $arrFollowSteps = explode(',',substr(substr($objstatus->follow_step_id_chain,1),0,-1));

            foreach($arrFollowSteps as $row){
                $step = $assignmentDao->getSSById($row);
                if($step){
                    $arrSteps[] = $step;

                    //Buil string
                    $strRoleId .= $step->performer_role_id_chain;
                }
            }
        }
        $this->view->assign('arrSteps', $arrSteps);
        $this->view->assign('strRoleId', $strRoleId);

        /*Bengin get tracking info*/
        $trackings = $orderDao->getTracking($order_id);
        $this->view->assign('trackings',$trackings);

        /**
         * Get status by tracking
        **/
        $arrStatus = array();
        foreach($trackings as $tracking){
            $status = $assignmentDao->getPSById($tracking->process_id);
            $arrStatus[$tracking->order_tracking_id] = $status->code;
        }
        $this->view->assign('arrStatus', $arrStatus);
        /*End tracking info*/

        /*Begin get order detail info*/
        /**
        * Get order detail info by current order
        **/
        $orderDetails = $orderDao->getOrderDetails($order_id);
        $this->view->assign('orderDetails', $orderDetails);

        $arrAllAtVal = array();
        $arrProducts = array();
        foreach($orderDetails as $d_order){
            $product = null;
            if(is_numeric($d_order->product_id)){
                $product = $cartDao->getProductById($d_order->product_id);
            }

            /**
            * Set default value
            **/
            $p_name = null;
            if($product){
                $p_name = trim($product->product_content_name)?$product->product_content_name:$product->product_admin_name;
            }
            $arrProducts[$d_order->order_detail_id] = $p_name;

            /**
            * Get attribute and value info for product
            **/
            $arrAtValId = Zend_Json::decode($d_order->product_value_type_id_chain);
            if($arrAtValId){
                $arrAtVal = array();
                $htmlAttVal = '<div>';
                foreach($arrAtValId as $key=>$row){
                    $attriubte = $attributeDao->getFEById($key);
                    $value = $valueDao->getFEById($row);
                    $attName = ($attriubte->attribute_type_content_name)?$attriubte->attribute_type_content_name:$attriubte->attribute_type_admin_name;
                    $valName = ($value->value_content_name)?$value->value_content_name:$value->value_type_name;
                    $htmlAttVal .= "<div style='display:table; width:100%;'><div style='float:left; width:50%; text-align:left;'><b>{$attName}:</b></div><div style='float:left; width:50%; text-align:left;'>{$valName}</div></div>";
                }
                $arrAllAtVal[$d_order->order_detail_id] = $htmlAttVal.'</div>';
            }
        }
        $this->view->assign('arrProducts',$arrProducts);
        $this->view->assign('arrAllAtVal',$arrAllAtVal);
        /*End order detail info*/

        /**
         * Get evaluation info where order status is close
        **/
        $order_status = $_status;
				
        if($order_status == 'finished'){
            /**Evaluation of order*/
            $order_exp = array();
            $order_exp['order_id'] = $order_id;
            $orderEval = $evaluationDao->getById($order_exp);
            $this->view->assign('orderEval', $orderEval);
        }

        if($request->isPost()){

            /**
            * Check for exception not permission
            **/
            if(!strstr($strRoleId, ','.$user->role_id.',')){
                return;
            }

            $process_id = $request->getPost('process_id');
            $order_tracking_remark = $request->getPost('order_tracking_remark', null);
            $order_tracking_cost = $request->getPost('order_tracking_cost', null);
            $order_tracking_date = $request->getPost('order_tracking_date', null);

            if(!$process_id){
                $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('tracking_not_found_next_process')
                );
                $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_tracking'));
            }

            $order = array(
                'process_id' => $process_id,
            );
            $orderDao->updateTracking($order, $order_id);

            $orderTracking= array(
                'order_id'              => $order_id,
                'process_id'            => $process_id,
                'order_tracking_date'   => ($order_tracking_date)?date('Y-m-d', strtotime($this->convertDateFormat($order_tracking_date))):date('Y-m-d'),
                'order_tracking_remark' => $order_tracking_remark,
                'order_tracking_cost'   => $order_tracking_cost
            );
            $orderDao->addTracking($orderTracking);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('tracking_save_success')
                );

            $arrRouteView = array(
                'user_name' => $user->user_name,
                'order_id' => $order_id
            );
            $this->_redirect($this->view->serverUrl().$this->view->url($arrRouteView, 'customer_customer_view'));
        }
    }

    public function editAction(){
        $request = $this->getRequest();

        $user_name = $request->getParam('user_name');

        /**
        * Check no login yet
        **/
        $auth = Zend_Auth::getInstance();
        $userSession = $auth->getIdentity();
        if (!$userSession) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Customer models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * User models access to data
        **/
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
        * Get user info
        **/
        $user = $userDao->getByUserName($user_name);
        $this->view->assign('user', $user);

        /**
         * Check allow action
        **/
        $isAllowAction = true;
        if(@$userSession->user_id != @$user->user_id){
            $isAllowAction = false;
            $this->view->assign('isAllowAction', $isAllowAction);
            return;
        }
        $this->view->assign('isAllowAction', $isAllowAction);

        /**
         * Get customer info follow user
        **/
        $customer = null;
        $flag = false;
        if($user){
            $customer = $customerDao->getCustomer($user->user_id);
        }
        $this->view->assign('customer', $customer);
        $this->view->assign('flag', $flag);

         if($request->isPost()){
            $full_name        = $request->getPost('full_name');
            $username         = $request->getPost('email');
            $email            = $request->getPost('email');
            $address          = $request->getPost('address');
            $city             = $request->getPost('city');
            $tel              = $request->getPost('tel');
            $shipping_name    = $request->getPost('shipping_name');
            $shipping_email   = $request->getPost('shipping_email');
            $shipping_address = $request->getPost('shipping_address');
            $shipping_city    = $request->getPost('shipping_city');
            $shipping_tel     = $request->getPost('shipping_tel');

            $customer = new Bizprofile_Models_Customer(array(
                    'customer_address'  => $address,
                    'customer_city'     => $city,
                    'customer_tel'      => $tel,
                    'shipping_name'     => $shipping_name,
                    'shipping_email'    => $shipping_email,
                    'shipping_address'  => $shipping_address,
                    'shipping_city'     => $shipping_city,
                    'shipping_tel'      => $shipping_tel,
            ));

            $customer->user_id = $user->user_id;
            
            $userInfo = new Core_Models_User(array(
                    'user_name' => $user->user_name,
                    'full_name' => $full_name,
                    'email'     => $user->email,
                    'role_id'   => $user->role_id,
                    'user_id'   => $user->user_id
            ));
            /**
             * Update user
            **/
            $userDao->update($userInfo);

            /**
             * Update user session
            **/
            $user->full_name = $full_name;
			
            /**
             * Update customer
            **/
         	if($customerDao->getCustomer($customer->user_id)){
                	$customerDao->updateCustomer($customer);	
                }
                else{
                	$customerDao->add($customer);	
                }

            /**
            * Redirect
            **/
            
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('customer_edit_success')
            );
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('user_name' => $user->user_name), 'customer_customer_edit'));
            
        }
    }

    public function evaluationAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();

        /**
        * Check no login yet
        **/
        $auth = Zend_Auth::getInstance();
        $user = $auth->getIdentity();
        if (!$user) {
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        if($request->isPost()){
            $order_id = $request->getPost('order_id');
            if($request->getPost('bEvaluated')){
                $buyer = true;
                $buyer_enterprise_id        = $request->getPost('enterprise_id');
                $buyer_user_id              = $request->getPost('buyer_id');
                $buyer_to_seller_evaluation = $request->getPost('point');
                $buyer_to_seller_feedback   = $request->getPost('evaluation');
                $enterprise_id              = $request->getPost('eval_enterprise_id');
                
                $evaluation_point = $buyer_to_seller_evaluation;

                $evaluations = new Shop_Models_Evaluation(array(
                    'order_id'                   => $order_id,
                    'buyer_user_id'              => $buyer_user_id,
                    'buyer_enterprise_id'        => $buyer_enterprise_id,
                    'buyer_to_seller_feedback'   => $buyer_to_seller_feedback,
                    'buyer_to_seller_evaluation' => $buyer_to_seller_evaluation,
                ));
            }
            if($request->getPost('sEvaluated')){
                $buyer = false;
                $seller_enterprise_id       = $request->getPost('enterprise_id');
                $seller_user_id             = $request->getPost('seller_id');
                $seller_to_buyer_evaluation = $request->getPost('point');
                $seller_to_buyer_feedback   = $request->getPost('evaluation');

                $customer_id                = $request->getPost('customer_id');
                /**
                * Check customer belong enterprise
                */
                $userAccount = $userAccountDao->getByUser($customer_id);
                $enterprise_id = null;
                if($userAccount){
                    $enterprise_id = $userAccount->enterprise_id;
                }
                $evaluation_point = $seller_to_buyer_evaluation;

                $evaluations = new Shop_Models_Evaluation(array(
                    'order_id'                   => $order_id,
                    'seller_user_id'             => $seller_user_id,
                    'seller_enterprise_id'       => $seller_enterprise_id,
                    'seller_to_buyer_feedback'   => $seller_to_buyer_feedback,
                    'seller_to_buyer_evaluation' => $seller_to_buyer_evaluation,
                ));
            }            
            if($request->getPost('update')){            	
                if($evaluationDao->update($evaluations, $buyer)){
                    if($enterprise_id){
                        /**
                        * Update evaluation and counter for enterprise
                        **/
                        $evaluationEnt = array(
                            'enterprise_id'    => $enterprise_id,
                            'evaluation_point' => $evaluation_point
                        );
                        $evaluationDao->updateEnt($evaluationEnt);
                    }else{
                        /**
                        * Update evaluation and counter for customer
                        **/
                        $evaluationCus = array(
                            'customer_id'      => $customer_id,
                            'evaluation_point' => $evaluation_point
                        );
                        $evaluationDao->updateCus($evaluationCus);
                    }

                    /*$this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('customer_evaluation_save_success')
                    );*/
                }else{
                    /*$this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('customer_evaluation_save_no_success')
                    );*/
                }
            }else{            	
                if($evaluationDao->add($evaluations)){
                    if($enterprise_id){
                        /**
                        * Update evaluation and counter for enterprise
                        **/
                        $evaluationEnt = array(
                            'enterprise_id'    => $enterprise_id,
                            'evaluation_point' => $evaluation_point
                        );
                        $evaluationDao->updateEnt($evaluationEnt);
                    }else{
                        /**
                        * Update evaluation and counter for customer
                        **/
                        $evaluationCus = array(
                            'customer_id'      => $customer_id,
                            'evaluation_point' => $evaluation_point
                        );                        
                        $evaluationDao->updateCus($evaluationCus);
                    }

                    /*$this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('customer_evaluation_save_success')
                    );*/
                }else{
                    /*$this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('customer_evaluation_save_no_success')
                    );*/
                }
            }
			if($request->getParam('list_action') == "list_action")
			{
            	$this->_redirect($this->view->serverUrl().$this->view->url(array('user_name' => $user->user_name), 'customer_customer_list'));
				
			}
			elseif ($request->getPost('adminViewOrder')){
				$this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_view'));
			}
			else 
			{
				$this->_redirect($this->view->serverUrl().$this->view->url(array('user_name' => $user->user_name,'order_id' => $order_id), 'customer_customer_view'));
			}
        }
    }

    public function evaluationUserAction(){
        $request = $this->getRequest();

        $lang    = $request->getParam('lang');
        $this->view->assign('lang', $lang);
        $enterprise_id = $request->getParam('enterprise_id');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
         * Evaluation models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('customer')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
        * Enterprise model access to db
        */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);
		
        $enterprise = $enterpriseDao->getById($enterprise_id);        
        $this->view->assign('enterprise', $enterprise);
        $this->view->assign('exp_id', $enterprise_id);
    }

    public function buyerAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();

        $lang    = $request->getParam('lang');
        $this->view->assign('lang', $lang);
        $user_id  = $request->getParam('user_id');        

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Evaluation models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('customer')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Order model access to db
        */
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise model access to db
        */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);        
        
        $strUId = ',';
        if($user_id){
            $userAccount = $userAccountDao->getById($user_id);
            foreach($userAccount as $u_id){
            	$strUId .= $u_id->user_id.',';
            }
        }
        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 10;
        $offset     = ($pageIndex - 1) * $perPage;
        $params = null;

        $buyer_exp['customer_id'] = $strUId;
        $buyerEval = $evaluationDao->orderEval($buyer_exp, $offset, $perPage);
        $total     = $evaluationDao->counOrderEval($buyer_exp);        
        
        //$buyerEval = $evaluationDao->getByEU($offset, $perPage, $buyer_exp);
        //$total     = $evaluationDao->countEU($buyer_exp);
        $sum        = $evaluationDao->sum($buyer_exp);

        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($buyerEval, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('buyerEval', $buyerEval);
        $this->view->assign('numBuyerEval', $total);
        $this->view->assign('sumBuyerEval', $sum);
        $this->view->assign('paginator', $paginator);

        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array('user_id' => $user_id), 'customer_evaluation_buyer'),
            'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
        ));
        
        /**
         * Get order and enterprise info
         * @param array @arrEntInfo store enterprise info of follow
         * @author quanvo
        **/
        $arrEntInfo	  = array();
        foreach($buyerEval as $b_row){            
            $enterprise = $enterpriseDao->getById($b_row->enterprise_id);
    		$arrEntItems = array(
    			'id' => $enterprise->id,
    			'name_vi' => $enterprise->company_name_vn,
    			'name_en' => $enterprise->company_name_en,
    		);
    		$arrEntInfo[$b_row->order_id] = $arrEntItems;
        }        
        $this->view->assign('arrEntInfo', $arrEntInfo);
    }
    
    public function sellerAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();

        $user_id = $request->getParam('user_id');
        $lang    = $request->getParam('lang');
        $this->view->assign('lang', $lang);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Evaluation models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('customer')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Order model access to db
        */
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise model access to db
        */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 10;
        $offset    = ($pageIndex - 1) * $perPage;
        $params    = null;

		$seller_exp['enterprise_id'] = $user_id;
		$sellerEval = $evaluationDao->orderEval($seller_exp, $offset, $perPage);
        $total      = $evaluationDao->counOrderEval($seller_exp);
        $sum        = $evaluationDao->sum($seller_exp, false);

        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($sellerEval, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('sellerEval', $sellerEval);
        $this->view->assign('numSellerEval', $total);
        $this->view->assign('sumSellerEval', $sum);
        $this->view->assign('paginator', $paginator);

        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array('user_id' => $user_id), 'customer_evaluation_seller'),
            'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
        ));

        /**
        * Get order invoice for seller
        **/
        $sellerInvoice = array();
        foreach($sellerEval as $s_row){
        	$order = $orderDao->getOrderById($s_row->order_id);
            $sellerInvoice[$s_row->order_id] = $order->order_invoice;
        }
        $this->view->assign('sellerInvoice', $sellerInvoice);

        /**
        * get customer info
        **/
        $sellerCus= array();
        foreach($sellerEval as $s_row){       
        	if($s_row->buyer_user_id){     
	        	$customer = $customerDao->getById($s_row->buyer_user_id);
	            $sellerCus[$s_row->buyer_user_id] = $customer;
        	}
        }
        $this->view->assign('sellerCus', $sellerCus);
    }
    
    public function userAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();

        $lang    = $request->getParam('lang');
        $this->view->assign('lang', $lang);

        $user_id      = $request->getParam('user_id');
        $isEnterprise = $request->getParam('isEnterprise');
        $this->view->assign('isEnterprise', $isEnterprise);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Evaluation models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('customer')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Order model access to db
        */
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise model access to db
        */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 10;
        $offset     = ($pageIndex - 1) * $perPage;
        $params = null;

        $buyer_exp['customer_id'] = ','.$user_id.',';
        $buyerEval = $evaluationDao->orderEval($buyer_exp, $offset, $perPage);
        $total     = $evaluationDao->counOrderEval($buyer_exp);        

        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($buyerEval, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('buyerEval', $buyerEval);
        $this->view->assign('numBuyerEval', $total);
        $this->view->assign('paginator', $paginator);

        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array('user_id' => $user_id), 'customer_evaluation_user'),
            'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
        ));
        
        /**
         * Get order and enterprise info
         * @param array @arrEntInfo store enterprise info of follow
         * @author quanvo
        **/
        $arrEntInfo	  = array();
        foreach($buyerEval as $b_row){            
            $enterprise = $enterpriseDao->getById($b_row->enterprise_id);
    		$arrEntItems = array(
    			'id' => $enterprise->id,
    			'name_vi' => $enterprise->company_name_vn,
    			'name_en' => $enterprise->company_name_en,
    		);
    		$arrEntInfo[$b_row->order_id] = $arrEntItems;
        }        
        $this->view->assign('arrEntInfo', $arrEntInfo);
    }
}